package logic

import (
	"context"
	"fmt"
	"math/rand"
	"time"
	"user_srv/models"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type SmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SmsLogic {
	return &SmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SmsLogic) Sms(in *user_srv.SmsRequest) (*user_srv.SmsResponse, error) {
	// todo: add your logic here and delete this line
	key := in.Phone
	code := fmt.Sprintf("%d", rand.Intn(9000)+1000)
	sms, err := pkg.Sms(in.Phone, code)
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}
	models.RDB.Set(models.Ctx, key, code, 5*time.Minute)
	return &user_srv.SmsResponse{}, nil
}
